package com.patrol.logisticsmanage.ui.tuijian;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.net.AppConfig;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.orders.OrderDetail;
import com.patrol.logisticsmanage.ui.orders.OrderDetailAdapter;
import com.patrol.logisticsmanage.ui.orders.OrderInfo;
import com.patrol.logisticsmanage.ui.orders.OrdersAdapter;

import java.lang.annotation.ElementType;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/tuijian")
public class TuijianActivity extends BaseActivity {

//    @BindView(R.id.startquery)
//    Button startquery;

    @BindView(R.id.rcy_tuijian)
    RecyclerView rcyTuijian;

    @BindView(R.id.rcy_todayorder)
    RecyclerView rcyTodayorder;

    @BindView(R.id.bmijianyi)
    TextView tvbmijianyi;

    @BindView(R.id.bmi)
    TextView bmiView;
    @Autowired
    String bmi;

    @BindView(R.id.reltotal)
    TextView tvReltotal;
    @BindView(R.id.danbztotal)
    TextView tvDanbztotal;
    @BindView(R.id.zhiftotal)
    TextView tvZhiftotal;
    @BindView(R.id.tanshhwtotal)
    TextView tvTanshhwtotal;
    @BindView(R.id.dangctotal)
    TextView tvDangctotal;
    @BindView(R.id.natotal)
    TextView tvNatotal;
    @BindView(R.id.gaitotal)
    TextView tvGaitotal;
    @BindView(R.id.pieChart)
    PieChart pieChart;

    Boolean ellip = false;

    OrderDetailAdapter orderDetailAdapter;
    OrderDetailAdapter todayDetailAdapter;
    List<OrderDetail> k = new ArrayList<>();
    List<OrderDetail> randList = new ArrayList<>();
    List<OrderDetail> todayList = new ArrayList<>();

    Map<String,Double> yingyangMap = new HashMap<>();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuijian);
        ButterKnife.bind(this);

        rcyTuijian.setLayoutManager(new LinearLayoutManager(mContext){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        orderDetailAdapter = new OrderDetailAdapter(mContext);
        orderDetailAdapter.showEmptyView(true);

        orderDetailAdapter.setList(randList);

        rcyTuijian.setAdapter(orderDetailAdapter);

        rcyTodayorder.setLayoutManager(new LinearLayoutManager(mContext){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        todayDetailAdapter = new OrderDetailAdapter(mContext);
        todayDetailAdapter.showEmptyView(true);

        todayDetailAdapter.setList(todayList);
        rcyTodayorder.setAdapter(todayDetailAdapter);
        yingyangMap.clear();
        bmiView.setText(bmi);
        Double bmitmp = 0d;
        try{
            bmitmp = Double.parseDouble(bmi.split(":")[1].split(" ")[0]);
        }catch (Exception ex){
ex.printStackTrace();
        }
        if(bmitmp<18.4)
            tvbmijianyi.setText("你的BMI指数较低，属于较瘦。高蛋白、高热量饮食绝对系健康增重者的首选。少食多餐、同补充消化酵素以增加对食物的消化吸收率亦都好重要。哪些是高蛋白、高热量食品？高蛋白：鸡蛋、牛奶、肉类、海鲜等，高热量：米饭、土豆、番薯、南瓜、芋头等。另外建议瘦弱的朋友，进行一些力量运动，如杠铃、哑铃等等。");
        else if(bmitmp<24 )
            tvbmijianyi.setText("你的BMI指数正常，是最好的身体状态。通过适当的健身来继续保持这种fit身材，当然男性朋友如果想练出性感人鱼线和健美八块腹肌，女性朋友想拥有前凸后翘S型曼妙身材的话，可以通过专业的运动完善身材的线条及健康的质量");
        else if(bmitmp<28)
            tvbmijianyi.setText("你BMI指数超重了，就是说你稍微有点胖了。实行“管的住嘴迈的开腿”的健身方法，少吃零食、甜膩、油炸、油煎之类高热量食物，多吃蔬菜水果和膳食纤维及富含营养但是低热量的食品，同时开始做有氧运动，类似于跑步、健身车、划船器、游泳等，提高代謝速率，加速消耗体内的脂肪和热量");
        else
            tvbmijianyi.setText("你BMI指数已经超标了，已经达到肥胖一族的标准。建议不能吃垃圾食品和过于油腻的食物，多吃富含营养但是低热量的食品,例如大豆、绿色蔬菜、无脂或低脂的牛奶、没有添加食用香料和奶精的燕麦片等，不喝酒，不喝饮料，多喝水，每天坚持1个小时以上的中等或高等强度运动，例如跑步、游泳、跳绳、登山等，当然要根据个人实际身体情况，可以一次完成，也可以分次进行");

//        tvbmijianyi.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(ellip){ //折叠
//                    tvbmijianyi.setEllipsize(null);
//                    tvbmijianyi.setSingleLine(false);
//                }else{
//                    tvbmijianyi.setLines(2);
//                    tvbmijianyi.setEllipsize(TextUtils.TruncateAt.END);
//                }
//                ellip = !ellip;
//            }
//        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        getData();
        orders();
    }

//    @OnClick({R.id.startquery})
//    public void query(View view) {
//        randomData();
//    }

    private void randomData(){
        yingyangMap.clear();
        Collections.shuffle(k);
        randList.clear();
        randList.addAll(k.subList(0,2));
        orderDetailAdapter.notifyDataSetChanged();
//        Double rel =0d;// Double.parseDouble(detail.getRel());
//        Double danbz =0d;//= Double.parseDouble(detail.getDanbz());
//        Double zhif =0d;//= Double.parseDouble(detail.getZhif());
//        Double tanshhw =0d;//= Double.parseDouble(detail.getTanshhw());
//        Double dangc =0d;//= Double.parseDouble(detail.getDangc());
//        Double na =0d;//= Double.parseDouble(detail.getNa());
//        Double gai =0d;//= Double.parseDouble(detail.getGai());
//        for(OrderDetail detail:randList){
//            rel += Double.parseDouble(null == detail.getRel()|| "".equals(detail.getRel())?"0":detail.getRel());
//            danbz += Double.parseDouble(null == detail.getDanbz()|| "".equals(detail.getDanbz())?"0":detail.getDanbz());
//            zhif += Double.parseDouble(null == detail.getZhif()|| "".equals(detail.getZhif())?"0":detail.getZhif());
//            tanshhw += Double.parseDouble(null == detail.getTanshhw()|| "".equals(detail.getTanshhw())?"0":detail.getTanshhw());
//            dangc += Double.parseDouble(null == detail.getDangc()|| "".equals(detail.getDangc())?"0":detail.getDangc());
//            na += Double.parseDouble(null == detail.getNa()|| "".equals(detail.getNa())?"0":detail.getNa());
//            gai += Double.parseDouble(null == detail.getGai()|| "".equals(detail.getGai())?"0":detail.getGai());
//        }
//        tvReltotal.setText("热量(千卡):" + String.format("%.2f", rel));
//        tvDanbztotal.setText("蛋白质(克):" + String.format("%.2f", danbz));
//        tvZhiftotal.setText("脂肪(克):"+String.format("%.2f", zhif));
//        tvTanshhwtotal.setText("碳水化物(克):" + String.format("%.2f", tanshhw));
//        tvDangctotal.setText("胆固醇(毫克):" + String.format("%.2f", dangc));
//        tvNatotal.setText("钠(毫克):" + String.format("%.2f", na));
//        tvGaitotal.setText("钙(毫克):" + String.format("%.2f", gai));
//        yingyangtotal.setText("热量:" + String.format("%.2f", rel) + "蛋白质:" + String.format("%.2f", danbz)+ "|脂肪:"+String.format("%.2f", zhif) +
//                "\n碳水化物:" + String.format("%.2f", tanshhw)+ "|胆固醇:" + String.format("%.2f", dangc) + "|盐:" + String.format("%.2f", na) + "\n钙:" + String.format("%.2f", gai));

    }

    public void getData(){
        BaseRequest.getInstance().getApiServise().cpdata()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<OrderDetail>>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<List<OrderDetail>> baseReponse) {
                        List<OrderDetail> result =  baseReponse.getResults();
                        k.clear();
                        k.addAll(result);
                        randomData();
                        pieData();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                        tBaseReponse.getCode();
                    }
                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                        e.printStackTrace();
                    }
                });
    }

    public void pieData(){
        Double rel =0d;// Double.parseDouble(detail.getRel());
        Double danbz =0d;//= Double.parseDouble(detail.getDanbz());
        Double zhif =0d;//= Double.parseDouble(detail.getZhif());
        Double tanshhw =0d;//= Double.parseDouble(detail.getTanshhw());
        Double dangc =0d;//= Double.parseDouble(detail.getDangc());
        Double na =0d;//= Double.parseDouble(detail.getNa());
        Double gai =0d;//= Double.parseDouble(detail.getGai());
        for(OrderDetail detail:k){
            rel += Double.parseDouble(null == detail.getRel()|| "".equals(detail.getRel())?"0":detail.getRel());
            danbz += Double.parseDouble(null == detail.getDanbz()|| "".equals(detail.getDanbz())?"0":detail.getDanbz());
            zhif += Double.parseDouble(null == detail.getZhif()|| "".equals(detail.getZhif())?"0":detail.getZhif());
            tanshhw += Double.parseDouble(null == detail.getTanshhw()|| "".equals(detail.getTanshhw())?"0":detail.getTanshhw());
            dangc += Double.parseDouble(null == detail.getDangc()|| "".equals(detail.getDangc())?"0":detail.getDangc());
            na += Double.parseDouble(null == detail.getNa()|| "".equals(detail.getNa())?"0":detail.getNa());
            gai += Double.parseDouble(null == detail.getGai()|| "".equals(detail.getGai())?"0":detail.getGai());
        }

        dangc = dangc/1000;
        na = na/1000;
        gai = gai/1000;
        Double total = danbz + zhif + tanshhw + dangc + na + gai;

        List<PieEntry> pieentrylist = new ArrayList<>();
        pieentrylist.add(new PieEntry((float) (danbz/total)*100,"蛋白质"));
        pieentrylist.add(new PieEntry((float)(zhif/total)*100,"脂肪"));
        pieentrylist.add(new PieEntry((float)(tanshhw/total)*100,"碳水化合物"));
        pieentrylist.add(new PieEntry((float)(dangc/total)*100,"胆固醇"));
        pieentrylist.add(new PieEntry((float)(na/total)*100,"钠"));
        pieentrylist.add(new PieEntry((float)(gai/total)*100,"钙"));

        PieDataSet pieDataSet = new PieDataSet(pieentrylist,"");
        pieDataSet.setColors(Color.parseColor("#ffccee"),Color.parseColor("#eecc4d"),Color.parseColor("#feb64d"),Color.parseColor("#ff7c7c"),Color.parseColor("#9287e7"),Color.parseColor("#60acfc"),Color.parseColor("#70aafc"));
        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData);
        pieData.setValueFormatter(new PercentFormatter());
        pieData.setValueTextColor(Color.parseColor("#FFFFFF"));
        pieData.setValueTextSize(10f);
        Description description= new Description();

        description.setText("");
        //把右下边的Description label 去掉，同学也可以设置成饼图说明
        pieChart.setDescription(description);

        //去掉中心圆，此时中心圆半透明
        pieChart.setHoleRadius(0f);
        //去掉半透明
        pieChart.setTransparentCircleAlpha(0);

        pieChart.setDrawEntryLabels(true);

        pieChart.invalidate();
    }

    Handler handler = new Handler();
    public void orders(){
        String userName = AppConfig.getString("userName");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String today = dateFormat.format(new Date());
//        today = "2020-12-22";
        BaseRequest.getInstance().getApiServise().yuangxfjl(userName,today + " 00:00:00",today + " 23:59:59")
//        BaseRequest.getInstance().getApiServise().cpdata()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<OrderInfo>>(mContext) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onSuccess(BaseReponse<List<OrderInfo>> baseReponse) {
                        todayList.clear();
                        List<OrderInfo> result =  baseReponse.getResults();
                        if(null != result && result.size()>0){
                            new Thread(()->{
                                for(OrderInfo info:result){
                                    try {
                                        orderDetails(todayList, info.getOutid());
                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }

                                Double rel =0d;// Double.parseDouble(detail.getRel());
                                Double danbz =0d;//= Double.parseDouble(detail.getDanbz());
                                Double zhif =0d;//= Double.parseDouble(detail.getZhif());
                                Double tanshhw =0d;//= Double.parseDouble(detail.getTanshhw());
                                Double dangc =0d;//= Double.parseDouble(detail.getDangc());
                                Double na =0d;//= Double.parseDouble(detail.getNa());
                                Double gai =0d;//= Double.parseDouble(detail.getGai());

                                for(OrderDetail detail:todayList){
                                    rel += Double.parseDouble(null == detail.getRel()|| "".equals(detail.getRel())?"0":detail.getRel());
                                    danbz += Double.parseDouble(null == detail.getDanbz()|| "".equals(detail.getDanbz())?"0":detail.getDanbz());
                                    zhif += Double.parseDouble(null == detail.getZhif()|| "".equals(detail.getZhif())?"0":detail.getZhif());
                                    tanshhw += Double.parseDouble(null == detail.getTanshhw()|| "".equals(detail.getTanshhw())?"0":detail.getTanshhw());
                                    dangc += Double.parseDouble(null == detail.getDangc()|| "".equals(detail.getDangc())?"0":detail.getDangc());
                                    na += Double.parseDouble(null == detail.getNa()|| "".equals(detail.getNa())?"0":detail.getNa());
                                    gai += Double.parseDouble(null == detail.getGai()|| "".equals(detail.getGai())?"0":detail.getGai());
                                }
                                Double finalRel = rel;
                                Double finalDanbz = danbz;
                                Double finalZhif = zhif;
                                Double finalTanshhw = tanshhw;
                                Double finalDangc = dangc;
                                Double finalNa = na;
                                Double finalGai = gai;
                                handler.post(()->{
                                    todayDetailAdapter.notifyDataSetChanged();
                                    tvReltotal.setText("    热量(千卡):" + String.format("%.2f", finalRel));
                                    tvDanbztotal.setText("    蛋白质(克):" + String.format("%.2f", finalDanbz));
                                    tvZhiftotal.setText("    脂肪(克):"+String.format("%.2f", finalZhif));
                                    tvTanshhwtotal.setText("    碳水化物(克):" + String.format("%.2f", finalTanshhw));
                                    tvDangctotal.setText("    胆固醇(毫克):" + String.format("%.2f", finalDangc));
                                    tvNatotal.setText("    钠(毫克):" + String.format("%.2f", finalNa));
                                    tvGaitotal.setText("    钙(毫克):" + String.format("%.2f", finalGai));
                                });

                            }).start();

                        }
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
                        tBaseReponse.getCode();
                    }
                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {
                        e.printStackTrace();
                    }
                });
    }

    public void orderDetails(List<OrderDetail> list,String outid) throws Exception{
        List<OrderDetail> result = BaseRequest.getInstance().getApiServise().xiaofjlxq(outid).execute().body().getResults();
        list.addAll(result);

    }
}
